package conf

import (
	"os"

	"gitee.com/bethink1501/24on-library/db"
	"gitee.com/bethink1501/24on-library/lib/jsontime"

	"gitee.com/bethink1501/24on-library/zconf"
	"gitee.com/bethink1501/24on-library/zlog"
	"gitee.com/bethink1501/24on-library/zredis"
	"github.com/spf13/viper"
)

type Config struct {
	Server   *Server      `json:"server"`
	Data     *Data        `json:"data"`
	Registry *Registry    `json:"registry"`
	Log      *zlog.Config `json:"log"`
}

type Server struct {
	Http struct {
		Network string            `json:"network"`
		Addr    string            `json:"addr"`
		Timeout jsontime.Duration `json:"timeout"`
	} `json:"http"`
	Grpc struct {
		Network string            `json:"network"`
		Addr    string            `json:"addr"`
		Timeout jsontime.Duration `json:"timeout"`
	} `json:"grpc"`
}

type Data struct {
	Mysql *db.Config     `json:"mysql"`
	Redis *zredis.Config `json:"redis"`
}

type Registry struct {
	Type string `json:"type"`
	Addr string `json:"addr"`
}

type OssConfig struct {
	Endpoint string `json:"endpoint"`
	AK       string `json:"ak"`
	SK       string `json:"sk"`
	Bucket   string `json:"bucket"`
}

func InitConfig() *Config {
	myConfig := &Config{}
	v := viper.New()
	v.SetConfigType("yaml")
	v.AddConfigPath(".")
	v.AddConfigPath("../configs")
	v.AddConfigPath("configs")
	env := os.Getenv("conf")
	if env == "" {
		v.SetConfigName("conf")
	} else {
		v.SetConfigName("conf_" + env)
	}

	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	if err := v.UnmarshalExact(myConfig, zconf.ViperOptions()); err != nil {
		panic(err)
	}
	return myConfig
}
